package com.woniu.common.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * packageName com.woniu.rabbit.utils
 *
 * @author zxyang3636
 * @version JDK 8
 * @className RabbitMsgUtil
 * @date 2024/7/30
 * @description TODO
 */

public class RabbitMsgUtil {

    public static <T> void sendMsg(RedisTemplate<String, Object> redisTemplate, RabbitTemplate rabbitTemplate,
                                   String exchange, String routingKey, T msg) {
        sendMsg(redisTemplate, rabbitTemplate, exchange, routingKey, msg, null);
    }

    public static <T> void sendMsg(RedisTemplate<String, Object> redisTemplate, RabbitTemplate rabbitTemplate,
                                   String exchange, String routingKey, T msg, String appId) {
        CorrelationData correlationData = new CorrelationData();
        Message message = new Message(JSON.toJSONBytes(msg));
        correlationData.setReturnedMessage(message);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedExchange(exchange);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedRoutingKey(routingKey);
        // 消息表中的id
        correlationData.getReturnedMessage().getMessageProperties().setAppId(appId);

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 1.生成token，并保存到redis
                String token = IdUtil.fastUUID();
                redisTemplate.opsForValue().set(token, token, 20, TimeUnit.MINUTES);
                // 2.生产消息时带token
                message.getMessageProperties().setMessageId(token);
                message.getMessageProperties().setAppId(appId);
                return message;
            }
        };
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, messagePostProcessor, correlationData);
    }
}
